/*
 * @copyright 2011 Gerald Jacobson
 * @license GNU General Public License
 * 
 * This file is part of GameTimer.
 *
 * GameTimer is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * GameTimer is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with GameTimer. If not, see <http://www.gnu.org/licenses/>.
 */
package org.amphiption.gametimer;

import org.amphiption.gametimer.adapter.PlayerAdapter;
import org.amphiption.gametimer.entity.TimerConfiguration;
import org.amphiption.gametimer.entity.TimerConfiguration.TimerType;
import org.amphiption.gametimer.service.ITimerService;
import org.amphiption.gametimer.service.ITimerService.TimerState;
import org.amphiption.gametimer.service.TimerService;
import org.amphiption.gametimer.service.TimerService.TimerServiceListener;
import org.amphiption.gametimer.service.TimerServiceBinder;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

/**
 * @author Amphiprion
 * 
 */
public class PlaySession extends Activity {
	private TimerConfiguration tc;
	private ITimerService service;
	private Button btPause;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.session);

		final TextView txtInfo = (TextView) findViewById(R.id.txtInfo);

		Intent i = getIntent();
		tc = (TimerConfiguration) i.getSerializableExtra("TIMER_CONFIGURATION");
		final Intent intent = new Intent(this, TimerService.class);
		intent.putExtra("TIMER_CONFIGURATION", tc);

		final Button btStop = (Button) findViewById(R.id.btStop);
		btStop.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				final boolean needResume = service.isRunning();
				if (needResume) {
					service.pause();
				}
				AlertDialog.Builder builder = new AlertDialog.Builder(PlaySession.this);
				builder.setMessage(getResources().getString(R.string.stop_message));
				builder.setCancelable(false).setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int id) {
						service.stop();
						PlaySession.this.setResult(RESULT_OK);
						PlaySession.this.finish();
					}
				});
				builder.setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
						if (needResume) {
							service.pause();
						}
					}
				});
				AlertDialog alert = builder.create();
				alert.show();
			}
		});
		final Button btNext = (Button) findViewById(R.id.btNextPlayer);
		btNext.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				service.changePlayerAsked();
			}
		});

		btPause = (Button) findViewById(R.id.btPause);
		btPause.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				service.pause();
			}
		});

		final TimerServiceListener listener = new TimerServiceListener() {
			@Override
			public void endReached() {
				try {
					Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
					MediaPlayer mMediaPlayer = new MediaPlayer();
					mMediaPlayer.setDataSource(PlaySession.this, alert);
					final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
					if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
						mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
						// player.setLooping(true);
						mMediaPlayer.prepare();
						mMediaPlayer.start();
					}
				} catch (Exception e) {
					Log.e(ApplicationConstants.PACKAGE, "", e);
				}
			}

			@Override
			public void warn() {
				//
			}

			@Override
			public void updateUi(final int counter) {
				PlaySession.this.runOnUiThread(new Runnable() {
					@Override
					public void run() {
						if (service.getType() == TimerType.TURN_COUNTER) {
							txtInfo.setText("" + counter);
						} else {
							String txt = "";
							int info = Math.round(counter / 1000.0f);
							int hour = info / 3600;
							if (hour > 0) {
								txt += hour + ":";
							}

							info = info - hour * 3600;
							int minute = info / 60;
							if (minute < 10) {
								txt += "0";
							}
							txt += minute + ":";
							info = info - minute * 60;
							int second = info;
							if (second < 10) {
								txt += "0";
							}
							txt += second;
							txtInfo.setText(txt);
						}
					}
				});
			}

			@Override
			public void stateChanged() {
				PlaySession.this.runOnUiThread(new Runnable() {
					@Override
					public void run() {
						AlertDialog.Builder builder = new AlertDialog.Builder(PlaySession.this);
						builder.setTitle(getResources().getText(R.string.choose_player_turn));

						builder.setAdapter(new PlayerAdapter(PlaySession.this, tc.getPlayers()), new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int item) {
								final TextView txtPlayer = (TextView) findViewById(R.id.txtPlyer);
								txtPlayer.setBackgroundColor(tc.getPlayers().get(item).getColor());
								txtPlayer.setText(tc.getPlayers().get(item).getName());
								service.startPlayer(item);
								dialog.dismiss();
							}
						});
						final AlertDialog alert = builder.create();
						alert.show();
					}
				});
			}

			@Override
			public void paused() {
				updatePauseButton();
			}

			@Override
			public void resumed() {
				updatePauseButton();
			}
		};

		ServiceConnection connection = new ServiceConnection() {
			@Override
			public void onServiceConnected(ComponentName name, IBinder binder) {
				service = ((TimerServiceBinder) binder).getService();
				service.setTimerServiceListener(listener);
				if (service.getState() == TimerState.INIT) {
					startService(intent);
				}
			}

			@Override
			public void onServiceDisconnected(ComponentName name) {
			}
		};

		bindService(intent, connection, Context.BIND_AUTO_CREATE);
	}

	private void updatePauseButton() {
		if (service.isRunning()) {
			btPause.setBackgroundDrawable(getResources().getDrawable(R.drawable.pause));
		} else {
			btPause.setBackgroundDrawable(getResources().getDrawable(R.drawable.play));
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
}
